package com.cysoft.starter.repeat.core.helper;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 玖零
 * @version V0.0.1
 * @project cysoft-spring-boot-starter-repeat
 * @package com.cysoft.starter.repeat.core.helper
 * @date 2025-03-02 23:53
 * @desc
 */
public class TokenHelper {

    private static final String TOKEN_HEADER_NAME = "Authorization";

    /**
     * 从请求参数、请求头和 Cookie 中获取 Token
     *
     * @param request              HttpServletRequest 对象
     * @param uniqueIdentification 唯一标识
     * @return 找到的 Token，如果未找到则返回 null
     */
    public static String getTokenFromRequest(HttpServletRequest request, String uniqueIdentification) {
        // 如果 uniqueIdentification 为空，使用默认的 TOKEN_HEADER_NAME
        if (uniqueIdentification == null || uniqueIdentification.isEmpty()) {
            uniqueIdentification = TOKEN_HEADER_NAME;
        }

        // 首先从请求参数中获取 Token
        String token = request.getParameter(uniqueIdentification);
        if (token != null && !token.isEmpty()) {
            return token;
        }

        // 接着从请求头中获取 Token
        token = request.getHeader(uniqueIdentification);
        if (token != null && !token.isEmpty()) {
            // 去除可能存在的 "Bearer " 前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            return token;
        }

        // 最后从 Cookie 中获取 Token
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (uniqueIdentification.equals(cookie.getName())) {
                    token = cookie.getValue();
                    if (token != null && !token.isEmpty()) {
                        return token;
                    }
                }
            }
        }

        return null;
    }
}
